package org.qloudgen.borg.task;

import org.apache.commons.lang.StringUtils;
import org.qloudgen.borg.CommonValues;
import org.qloudgen.borg.beans.CacheBean;
import org.qloudgen.borg.beans.TaskBean;
import org.qloudgen.borg.messaging.message.TaskMessage;
import org.qloudgen.borg.metadb.DefaultImpl;

public final class TaskUtils {
	
	/*
	 * clear cache by ds_no ,func_no,cluster_id
	 */
	public static void clearCache(String funcNo, String dsNo, String clusterID){
		
		DefaultImpl.deleteCacheByFunc(new CacheBean().setClusterID(clusterID)
											 .setDsNo(dsNo)
							                 .setFuncNo(funcNo));
		
	}
	
	/*
	 * clear cache by ds_no ,func_no,cluster_id, params
	 */
	public static void clearCache(String funcNo, String dsNo, String clusterID, String params){
		
		DefaultImpl.deleteCacheByTask(new CacheBean().setClusterID(clusterID)
											   .setDsNo(dsNo)
								               .setFuncNo(funcNo)
								               .setParams(params));

	}
	
	/*
	 * send task to queue
	 */
	public static void sendTask(TaskMessage task){
		
		// get cache_id from metadb
		String newCacheID = DefaultImpl.getCacheID();
		
		task.setCacheID(newCacheID);
		
		if (StringUtils.isEmpty(task.getTaskNo())) {
		// new task
			
			// insert task to metadb
			String taskNo = DefaultImpl.insertTask(task);
			
			task.setTaskNo(taskNo);
		} else {
		// old task
			
			// update status
			DefaultImpl.updateTaskStatus(new TaskBean().setTaskNo(task.getTaskNo()).setCacheID(newCacheID),CommonValues.TASK_STATUS_INQUEUE);
			
		}
		
		// submit to task queue
		CommonValues.sender.sendMessage(task);			

	}
	
	/*
	 *  get cache by func_no,ds_no,cluster_id,params
	 */
	public static String getCache(CacheBean cache){
		
		return DefaultImpl.getCache(cache);
	}
}
